package cn.cxy.cropdemo

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.qw.soul.permission.SoulPermission
import com.qw.soul.permission.bean.Permission
import com.qw.soul.permission.callbcak.CheckRequestPermissionListener
import com.soundcloud.android.crop.Crop
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File


class MainActivity : AppCompatActivity() {
    private val sourceImageUri = Uri.fromFile(
            File(Environment.getExternalStorageDirectory().absolutePath + "/1/test.jpg"))
    private val destImageUri = Uri.fromFile(
            File(Environment.getExternalStorageDirectory().absolutePath + "/1/test3.jpg"))

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener { applyPermissionAndCrop() }
    }

    private fun applyPermissionAndCrop() {
        SoulPermission.getInstance()
                .checkAndRequestPermission(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        object : CheckRequestPermissionListener {
                            override fun onPermissionOk(permission: Permission) {
                                cropImage()
                            }

                            override fun onPermissionDenied(permission: Permission) {
                            }
                        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, result: Intent?) {
        super.onActivityResult(requestCode, resultCode, result)
        if (requestCode == Crop.REQUEST_CROP && resultCode == Activity.RESULT_OK) {
            Glide.with(this)
                    .load(destImageUri)
                    .skipMemoryCache(true)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(imageView)

        }
    }

    fun cropImage() {
        Crop.of(sourceImageUri, destImageUri).asPng(true)
                .asSquare().withAspect(300, 300).withMaxSize(600, 800).start(this)
    }
}